<template>
  <div class="reservation">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>预定申请管理</span>
          <div class="header-buttons">
            <el-button type="primary" @click="handleAdd">新建预定</el-button>
          </div>
        </div>
      </template>

      <el-table :data="reservationList" style="width: 100%">
        <el-table-column prop="id" label="预定ID" width="100" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="carInfo" label="预定车辆" width="180" />
        <el-table-column prop="startDate" label="预定开始日期" width="180" />
        <el-table-column prop="endDate" label="预定结束日期" width="180" />
        <el-table-column prop="estimatedAmount" label="预计金额" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button 
              size="small" 
              type="success" 
              v-if="scope.row.status === '待审核'"
              @click="handleApprove(scope.row)"
            >
              审核通过
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              v-if="scope.row.status === '待审核'"
              @click="handleReject(scope.row)"
            >
              拒绝
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              v-if="scope.row.status === '已通过'"
              @click="handleConfirm(scope.row)"
            >
              确认预定
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建预定对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新建预定"
      width="500px"
    >
      <el-form :model="reservationForm" label-width="100px" :rules="rules" ref="reservationFormRef">
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="reservationForm.customerId" placeholder="请选择客户">
            <el-option
              v-for="customer in customerOptions"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆" prop="carId">
          <el-select v-model="reservationForm.carId" placeholder="请选择车辆">
            <el-option
              v-for="car in availableCars"
              :key="car.id"
              :label="car.brand + ' ' + car.model"
              :value="car.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="reservationForm.startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="reservationForm.endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="租赁总金额" prop="money">
          <el-input-number 
            v-model="reservationForm.money" 
            :min="0" 
            :precision="2" 
            :step="100"
            placeholder="请输入租赁总金额"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交预定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const reservationList = ref([])

// 获取预定申请列表
const fetchReservationList = async () => {
  try {
    const token = localStorage.getItem('Token')
    const url = new URL('http://localhost:8080/rental/list')
    
    // 添加分页参数
    url.searchParams.append('page', currentPage.value)
    url.searchParams.append('size', pageSize.value)
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    if (result.code === 200) {
      // 转换数据结构
      reservationList.value = (result.data.records || []).map(rental => ({
        id: rental.id,
        customerName: rental.customerName,
        carInfo: rental.carInfo,
        startDate: rental.startRentalTime,
        endDate: rental.endRentalTime,
        estimatedAmount: rental.money,
        status: getStatusText(rental.status)
      }))
      total.value = result.data.total || 0
      currentPage.value = result.data.current || 1
      pageSize.value = result.data.size || 10
    } else {
      throw new Error(result.message || '获取预定申请列表失败')
    }
  } catch (error) {
    console.error('获取预定申请列表失败：', error)
    ElMessage.error('获取预定申请列表失败：' + error.message)
  }
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchReservationList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchReservationList()
}

// 模拟客户和车辆选项数据
const customerOptions = ref([])
const availableCars = ref([])

// 获取客户列表
const fetchCustomerList = async () => {
  try {
    const token = localStorage.getItem('Token')
    const response = await fetch('http://localhost:8080/customers/names', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    if (result.code === 200) {
      // 将字符串数组转换为对象数组
      customerOptions.value = (result.data || []).map((name, index) => ({
        id: index + 1,
        name: name
      }))
    } else {
      throw new Error(result.message || '获取客户列表失败')
    }
  } catch (error) {
    console.error('获取客户列表失败：', error)
    ElMessage.error('获取客户列表失败：' + error.message)
  }
}

// 获取车辆列表
const fetchCarList = async () => {
  try {
    const token = localStorage.getItem('Token')
    const response = await fetch('http://localhost:8080/car/names', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    if (result.code === 200) {
      // 将字符串数组转换为对象数组
      availableCars.value = (result.data || []).map((name, index) => ({
        id: index + 1,
        brand: name,
        model: ''
      }))
    } else {
      throw new Error(result.message || '获取车辆列表失败')
    }
  } catch (error) {
    console.error('获取车辆列表失败：', error)
    ElMessage.error('获取车辆列表失败：' + error.message)
  }
}

const dialogVisible = ref(false)
const reservationFormRef = ref(null)
const reservationForm = reactive({
  customerId: '',
  carId: '',
  startDate: '',
  endDate: '',
  money: 0
})

const rules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  carId: [{ required: true, message: '请选择车辆', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  money: [{ required: true, message: '请输入租赁总金额', trigger: 'blur' }]
}

const handleAdd = () => {
  const today = new Date()
  const formattedDate = today.toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
  
  Object.assign(reservationForm, {
    customerId: '',
    carId: '',
    startDate: formattedDate,
    endDate: '',
    money: 0
  })
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!reservationFormRef.value) return
  
  await reservationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const token = localStorage.getItem('Token')
        const response = await fetch('http://localhost:8080/rental/add', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Token': token
          },
          body: JSON.stringify({
            customerName: customerOptions.value.find(c => c.id === reservationForm.customerId)?.name,
            carInfo: availableCars.value.find(c => c.id === reservationForm.carId)?.brand,
            startRentalTime: reservationForm.startDate,
            endRentalTime: reservationForm.endDate,
            money: reservationForm.money,
            status: 0  // 初始状态为待审核
          })
        })

        if (response.status === 401) {
          localStorage.removeItem('Token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          return
        }

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success('预定申请提交成功')
          dialogVisible.value = false
          // 刷新列表
          fetchReservationList()
        } else {
          throw new Error(result.message || '提交失败')
        }
      } catch (error) {
        console.error('提交失败：', error)
        ElMessage.error('提交失败：' + error.message)
      }
    }
  })
}

const handleApprove = (row) => {
  ElMessageBox.confirm('确定通过该预定申请吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(async () => {
    try {
      const token = localStorage.getItem('Token')
      // 确保状态值是有效的整数
      const currentStatus = parseInt(row.status) || 0
      const newStatus = currentStatus + 1
      
      if (isNaN(newStatus)) {
        throw new Error('无效的状态值')
      }

      const response = await fetch(`http://localhost:8080/rental/updateRentalStatus/${row.id}?status=${newStatus}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Token': token
        }
      })

      if (response.status === 401) {
        localStorage.removeItem('Token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('审核通过成功')
        // 刷新列表
        fetchReservationList()
      } else {
        throw new Error(result.message || '审核失败')
      }
    } catch (error) {
      console.error('审核失败：', error)
      ElMessage.error('审核失败：' + error.message)
    }
  })
}

const handleReject = (row) => {
  ElMessageBox.confirm('确定拒绝该预定申请吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const token = localStorage.getItem('Token')
      const response = await fetch(`http://localhost:8080/rental/updateRentalStatus/${row.id}?status=-1`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Token': token
        }
      })

      if (response.status === 401) {
        localStorage.removeItem('Token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('已拒绝该预定申请')
        // 刷新列表
        fetchReservationList()
      } else {
        throw new Error(result.message || '操作失败')
      }
    } catch (error) {
      console.error('操作失败：', error)
      ElMessage.error('操作失败：' + error.message)
    }
  })
}

const handleConfirm = (row) => {
  ElMessageBox.confirm('确定确认该预定吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    // 这里添加确认预定逻辑
    ElMessage.success('预定确认成功')
  })
}

// 添加状态码转换函数
const getStatusText = (status) => {
  const statusMap = {
    '-1': '已拒绝',
    0: '待审核',
    1: '进行中',
    2: '已完成'
  }
  return statusMap[status] || '未知状态'
}

// 修改状态类型映射
const getStatusType = (status) => {
  const statusMap = {
    '已拒绝': 'danger',
    '待审核': 'warning',
    '进行中': 'primary',
    '已完成': 'success'
  }
  return statusMap[status] || 'info'
}

// 在组件挂载时获取预定申请列表、客户列表和车辆列表
onMounted(() => {
  fetchReservationList()
  fetchCustomerList()
  fetchCarList()
})
</script>

<style scoped>
.reservation {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 添加分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 